import {defineStore} from "pinia";
import Cookies from "js-cookie";
import {ref} from 'vue'

const remember=ref(false)
// 定制存储【7:7天】
const cookiesStorage = {
	setItem (key, state) {
		console.log(`setItem ${key} -- ${state}`)
		//把JSON转换成JS对象
		let myState=JSON.parse(state)
		if(remember.value){
			return Cookies.set(key, myState.token, { expires: 7 })
		}else {
			return Cookies.set(key, myState.token)
		}
	},
	getItem (key) {
		return JSON.stringify({
			token: Cookies.get(key),
		})
	},
}

export const useTokenStore=defineStore('token',{
	//存数据的地方
	state(){
		return{
			token:''
		}
	},
	//actions里面存放方法
	actions:{
		setToken(newToken,rem){
			// localStorage.setItem('study1','java')
			// sessionStorage.setItem('study2','ui')
			this.token=newToken
			remember.value=rem
		},
		removeToken(){
			this.token=''
		}
	},
	persist: {
		enabled: true, // 开启缓存  默认会存储在本地localstorage
		storage:cookiesStorage
	}
})